import React, { useEffect, useState } from 'react';

import { connect, Dispatch } from 'umi';
import { ConnectState } from '@/models/connect';
import { Card, Input, Tag, Tree, Empty } from 'antd';
import { DataNode } from 'rc-tree/lib/interface';

import { RoleTableListItem } from '@/pages/Information/type';
import { debounce } from 'lodash';

export interface RoleDataType {
  projectId: string;
  roleId: string;
  roleName: string;
}

interface RoleProps {
  rolesParentList: Array<RoleTableListItem>;
  roles: Array<RoleTableListItem>;
  dispatch: Dispatch;
  getSubmitRoleKeys: (value: any) => void;
}

const RoleRight: React.FC<RoleProps> = (props) => {
  const { roles, rolesParentList, dispatch, getSubmitRoleKeys } = props;
  const [expandedKeys, setExpandedKeys] = useState<Array<any>>([]); // 展开指定的树节点
  const [searchValue, setSearchValue] = useState<string>(''); // 搜索关键词
  const [filterTreeData, setFilterTreeData] = useState<Array<any>>([]); // 关键词过滤后的树形结构数据
  const [roleKeys, setRoleKeys] = useState<Array<string>>([]); // 勾选的角色

  // 转换分配角色数据为 树形结构数据
  const treeData: Array<DataNode> = rolesParentList
    .map((value: RoleTableListItem) => {
      const key = value.id;
      const treeData: DataNode = { title: value.name, key: String(key)};
      const children: Array<DataNode> = [];
      roles.forEach((role: RoleTableListItem) => {
        if (role.projectId === key) {
          const tree: DataNode = { title: role.name, key: `${key}-${role.id}` }; // 父子级存在相同key, 采用添加父级id
          children.push(tree);
        }
      });
      if (children.length) {
        treeData.children = children;
      }
      return treeData;
    })
    .filter((v) => v.children);
  // 展开搜索到的内容节点
  const serach = debounce((value: string) => {
    setSearchValue(value);

    if (value) {
      treeData.map((item) => {
        if (item.children) {
          item.children = item.children.filter((v: any) => v.title.indexOf(value) > -1);
        }
        return item;
      });
      const filterArr = treeData.filter((v: any) => v.children.length);
      const expandedArr: Array<string> = [];
      filterArr.forEach((item: any) => {
        expandedArr.push(item.key);
      });
      setExpandedKeys(expandedArr);
      setFilterTreeData(filterArr);
    }
  }, 1000);

  // 搜索框输入值变化
  const onSearchChange = (e: any) => {
    e.persist();
    serach(e.target.value);
  };


  // 选中角色
  const onCheck = (checkedKeys: any) => {
    const checkedKeyList = checkedKeys.filter((key: string) => {
      if (key.indexOf('-')) {
        // 只取子级的ID
        const selectId = key.split('-')[1];
        return roles.map((p) => p.id).includes(Number(selectId));
      }
      return false;
    });
    setRoleKeys(checkedKeyList); // 获得勾选项
    getSubmitRoleKeys(checkedKeyList); // 传递到父组件
  };

  // 删除选中角色
  const onClose = (key: any) => {
    const arr = roleKeys.map((v) => v);
    arr.splice(
      arr.findIndex((v) => v === key),
      1,
    );
    setRoleKeys(arr);
    getSubmitRoleKeys(arr); // 传递到父组件
  };

  useEffect(() => {
    // 获取分配角色列表
    if (roles.length === 0) {
      dispatch({
        type: 'userManage/fetchRole',
      });
    }
  }, []);

  return (
    <div style={{ display: 'flex' }}>
      <Card
        title={<Input placeholder='搜索角色' size='small' onChange={onSearchChange} allowClear />}
        style={{ width: 300, marginRight: 20 }}
        size='small'
      >
        <Tree
          checkedKeys={roleKeys}
          checkable
          onCheck={onCheck}
          onExpand={setExpandedKeys}
          expandedKeys={expandedKeys}
          treeData={searchValue ? filterTreeData : treeData}
        />
        {searchValue && filterTreeData.length === 0 && (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='无搜索结果' />
        )}
      </Card>
      <Card title='已选择' style={{ flex: 1 }} size='small'>
        {roleKeys.map((key:any) => {
          let childrenID = key;
          const keys:string[] = key.split('-')
          if (keys.length >1) {
            childrenID = keys[1];
          }
          const roleData = roles.filter((role) => role.id === Number(childrenID))[0];
          return (
            <Tag color='green' key={key} closable onClose={() => onClose(key)} style={{ marginBottom: 10 }}>
              {roleData.name}
            </Tag>
          );
        })}
        {roleKeys.length === 0 ? <Empty description='暂无选择角色' /> : ''}
      </Card>
    </div>
  );
};

export default connect(({ userManage }: ConnectState) => ({
  rolesParentList: userManage.rolesParentList || [],
  roles: userManage.roles || [],
}))(RoleRight);
